package com.kongjs.common.datasource.aspect;

import com.kongjs.common.datasource.annotation.DynamicDataSource;
import com.kongjs.common.datasource.component.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据源切换切面
 */
@Aspect
@Component
public class DynamicDataSourceAspect {
    @Around("@within(com.kongjs.dynamic.datasource.annotation.DynamicDataSource) || @annotation(com.kongjs.dynamic.datasource.annotation.DynamicDataSource)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 方法优先
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DynamicDataSource dynamicDataSource = method.getAnnotation(DynamicDataSource.class);
        if (dynamicDataSource == null) {
            // 若方法上没有注解，检查类上是否有注解
            Class<?> targetClass = point.getTarget().getClass();
            dynamicDataSource = targetClass.getAnnotation(DynamicDataSource.class);
        }
        if (dynamicDataSource != null) {
            try {
                // 切换数据源
                String key = dynamicDataSource.value();
                DynamicDataSourceContextHolder.setDataSourceKey(key);
                return point.proceed();
            } finally {
                DynamicDataSourceContextHolder.clearDataSourceKey();
            }
        }
        return point.proceed();
    }
}
